package com.flycms.web.cms;

import com.flycms.core.entity.PageVo;
import com.flycms.core.entity.RestDataVo;
import com.flycms.module.cms.model.Custom;
import com.flycms.module.cms.model.Order;
import com.flycms.module.cms.param.CustomParam;
import com.flycms.module.cms.param.NewOrder;
import com.flycms.module.cms.param.OrderParam;
import com.flycms.module.cms.service.CmsOrderService;
import com.flycms.module.cms.service.CustomService;
import com.flycms.utils.ConvertUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class CmsController {

    @Autowired
    private CustomService customService;
    @Autowired
    private CmsOrderService cmsOrderService;

    /**
     * 客戶提交申請
     * @param custom
     * @return
     */
    @PostMapping("/custom/save")
    public RestDataVo customSave(@RequestBody Custom custom){
        try{
            customService.insert(custom);
        }  catch (Exception e) {
            log.error("客戶提交信息異常:",e);
            return RestDataVo.ERROR("保存失敗");
        }
        return RestDataVo.OK("保存成功");
    }

    /**
     * 查詢客戶提交的申請
     * @param param 查詢參數
     * @return 分頁結果
     */
    @GetMapping("/system/custom/page")
    public RestDataVo CustomPage(CustomParam param){
        PageVo<Custom> page = customService.queryByPage(param);
        return RestDataVo.PAGE(page.getList(),page.getPageNum(),param.getPageSize(),page.getCount());
    }

    /**
     * 後台審核
     * @param order 訂單信息
     * @return 保存結果
     */
    @PostMapping("/system/order/save")
    public RestDataVo orderSave(@RequestBody Order order){
        try{
            cmsOrderService.insert(order);
        }  catch (Exception e) {
            return RestDataVo.ERROR("保存失敗");
        }
        return RestDataVo.OK("保存成功");
    }

    /**
     * 新订单保存
     * @param order 訂單信息
     * @return 保存結果
     */
    @PostMapping("/custom/order/save")
    public RestDataVo cusOrderSave(@RequestBody NewOrder order){
        try{
            customService.insert(order);
            cmsOrderService.insert(order);
        }  catch (Exception e) {
            return RestDataVo.ERROR("保存失敗");
        }
        return RestDataVo.OK("保存成功");
    }

    /**
     * 確認發貨
     * @param id 客戶提交申請的ID
     * @return 操作結果
     */
    @PutMapping("/system/order/send/{id}")
    public RestDataVo orderSave(@PathVariable("id") Long id){
        try{
            cmsOrderService.send(id);
        }  catch (Exception e) {
            return RestDataVo.ERROR("操作失敗");
        }
        return RestDataVo.OK("操作成功");
    }

    /**
     * 獲取需要發貨的列表
     * @param param 參數
     * @return 返回結果
     */
    @GetMapping("/system/order/page")
    public RestDataVo orderPage(OrderParam param){
        PageVo<Order> page = cmsOrderService.queryByPage(param);
        List<Order> orders = page.getList();
        if(CollectionUtils.isEmpty(orders)){
            return RestDataVo.PAGE(Lists.newArrayList(),page.getPageNum(),param.getPageSize(),page.getCount());
        }
        //计算剩余时间
        List<NewOrder> newOrders = Lists.newArrayList();
        orders.forEach(o -> {
            NewOrder newOrder = ConvertUtils.sourceToTarget(o, NewOrder.class);
            newOrder.setOrderId(o.getId());
            Date now = new Date();
            long date = o.getSendTime().getTime() - now.getTime();
            if(date <= 0){
                newOrder.setRemainingTime("0");
            } else {
                long day = date / (1000 * 60 * 60 * 24);
                long hour = (date / (1000 * 60 * 60) - day * 24);
                long min = ((date / (60 * 1000)) - day * 24 * 60 - hour * 60);
                //long s = (date/1000 - day*24*60*60 - hour*60*60 - min*60);
                newOrder.setRemainingTime(" " +  day + "天" + hour + "小时" + min + "分钟");
            }
            newOrders.add(newOrder);
        });
        //填充用户信息
        List<Long> customId = orders.stream()
                .map(Order::getCustomId)
                .distinct()
                .collect(Collectors.toList());
        List<Custom> customs = customService.selectByIds(customId);
        if(CollectionUtils.isEmpty(customs)){
            return RestDataVo.PAGE(newOrders,page.getPageNum(),param.getPageSize(),page.getCount());
        }
        Map<Long, Custom> customMap = customs.stream()
                .collect(Collectors.toMap(Custom::getId, Function.identity(), (v1, v2) -> v1));
        newOrders.forEach(o -> {
            Custom custom = customMap.get(o.getCustomId());
            if(Objects.nonNull(custom)){
                o.setCustomName(custom.getCustomName());
                o.setCustomAddress(custom.getCustomAddress());
                o.setCustomEmail(custom.getCustomEmail());
                o.setCustomPhone(custom.getCustomPhone());
            }
        });
        return RestDataVo.PAGE(newOrders,page.getPageNum(),param.getPageSize(),page.getCount());
    }

}
